<?php

namespace app\admin\controller;

use app\admin\validate\Project as ProjectValide;
use app\common\model\Disease;
use app\common\model\Project as ProjectModel;
use think\App;

class Project extends Base
{

    protected $project;

    public function __construct(App $app, ProjectModel $project)
    {
        parent::__construct($app);
        $this->project = $project;
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $result = $this->project->select();
            ajaxSuccess($result);
        }
        return $this->fetch();
    }

    public function disease()
    {
        if ($this->request->isAjax()) {
            $position = $this->request->get('position', 1);
            $list = Disease::where('project_id', 2)->with('type')->where('position', $position)->select();
            $newList = [];
            foreach ($list as $item) {
                $newList[$item['type']['title']][] = $item;
            }
            ajaxSuccess($newList);
        }
        return $this->fetch();
    }

    public function save(ProjectValide $projectValide)
    {
        if (isAjax()) {
            $postData = $this->request->post(['id'=>1, 'title'=>'', 'start_date'=>'', 'end_date'=>'', 'length'=>'', 'structure'=>'','cad'=>'', 'file_xlsx'=>'']);
            $valid = $projectValide->check($postData);
            if (!$valid) ajaxError($projectValide->getError());
            $exits = $this->project->where('id', $postData['id'])->count();
            if(!$exits) ajaxError('暂未添加数据');

            $result = $this->project->update($postData);
            if (!$result) ajaxError('保存失败');
            ajaxSuccess();
        }
    }


}

